package com.leetcode.partition4;

import java.io.*;
import java.util.*;

/**
 * @author `RKC`
 * @date 2021/8/15 8:49
 */
public class LC332重新安排行程 {

    private static final int N = 310;
    private static int[][] graph = new int[N][N];
    private static Set<String> set = new TreeSet<>();
    private static Map<String, Integer> map1 = new HashMap<>(N);
    private static Map<Integer, String> map2 = new HashMap<>(N);
    private static List<String> answer = new ArrayList<>(N);

    private static int n = 0, idx = 0;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        int n = Integer.parseInt(reader.readLine());
        List<List<String>> tickets = new ArrayList<>(n);
        while (n-- > 0) {
            String[] ss = reader.readLine().split(" ");
            List<String> ticket = new ArrayList<>(2);
            ticket.add(ss[0]);
            ticket.add(ss[1]);
            tickets.add(ticket);
        }
        writer.write(findItinerary(tickets) + "\n");
        writer.flush();
    }

    public static List<String> findItinerary(List<List<String>> tickets) {
        for (List<String> ticket : tickets) {
            String from = ticket.get(0), to = ticket.get(1);
            set.add(from);
            set.add(to);
        }
        n = set.size();
        //分配编号
        for (String s : set) {
            map2.put(idx, s);
            map1.put(s, idx++);
        }
        for (List<String> ticket : tickets) {
            int idx1 = map1.get(ticket.get(0)), idx2 = map1.get(ticket.get(1));
            graph[idx1][idx2]++;
        }
        int start = map1.get("JFK");
        dfs(start);
        Collections.reverse(answer);
        return answer;
    }

    private static void dfs(int u) {
        for (int i = 0; i < N; i++) {
            if (graph[u][i] > 0) {
                graph[u][i]--;
                dfs(i);
            }
        }
        answer.add(map2.get(u));
    }
}
